<template>
  <el-dialog title="权限管理" :visible="visibleDialog" @close="closeFn">
    <el-tree
      ref="tree"
      :data="roleList"
      show-checkbox
      node-key="id"
      :props="{label:'title'}"
    />

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="editFn">确 定</el-button>
      <el-button @click="closeFn">取 消</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getPermission } from '@/api/permission'
import { listTreeTool } from '@/utils/index'
import { updateRoleList, editRoleListNumber } from '@/api/roleAdmin'

export default {
  props: {
    visibleDialog: {
      default: false,
      type: Boolean
    }, userId: {
      default: 0,
      type: Number
    }
  },
  data() {
    return {
      checkList: [],
      roleList: []
    }
  },
  async created() {
    // 获取权限列表
    const res = await getPermission({
      _start: 0,
      _limit: 100
    })

    this.roleList = listTreeTool(res.data, '0')
  },
  methods: {
    // 编辑权限
    async editFn() {
      // tree组件的选中复选框的方法
      const permissions = this.$refs.tree.getCheckedKeys()
      // 调用修改角色管理接口
      await updateRoleList({
        id: this.userId,
        permissions
      })
      this.closeFn()
    },
    //  实现回填功能
    async getRoleDet() {
      // 获取指定角色并传入id

      const res = await editRoleListNumber(this.userId)
      // console.log(111, res)
      // 权限数据回填
      this.checkList = res.data.permissions.map(item => {
        // console.log(111, item.id)
        return item.id
      })
      // 调用tree组件的回显方法
      this.$refs.tree.setCheckedKeys(this.checkList)
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:visibleDialog', false)
      //   this.$refs.formData.resetFields()
      this.checkList = []
    }
  }
}
</script>
<style scoped>
.el-checkbox{
  display: block;
  margin-top: 10px;
}
</style>
